package com.alfayun.fiscalriskanalysis.report;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alfayun.fiscalriskanalysis.common.HttpBadRequestException;
import com.alfayun.fiscalriskanalysis.common.HttpNotFoundException;

@Controller
@RequestMapping("/admin/report")
public class ReportManageController {
	
	@Autowired
	private ReportService service;
	
	@GetMapping("/list")
	public String list() {
		return "admin/report/report-list";
	}
	
	@ResponseBody
	@GetMapping("/list/data")
	public Map<String, List<Report>> listData() {
		Map<String, List<Report>> map = new HashMap<>();
		map.put("data", service.list());
		return map;
	}
	
	@ResponseBody
	@GetMapping("/queryById/{id}")
	public Report queryById(@PathVariable int id) throws HttpNotFoundException {
		try {
			return service.queryById(id);
		} catch (NoSuchReportException e) {
			throw HttpNotFoundException.build(e);
		}
	}
	
	@ResponseBody
	@RequestMapping("/add")
	public Report newReport(@RequestBody Report reportSpec) {
		return service.newReport(reportSpec);
	}
	
	@ResponseBody
	@DeleteMapping("/delete/{id}")
	public void deleteReport(@PathVariable int id) {
		service.deleteReport(id);
	}

	@ResponseBody
	@PutMapping("/update/{id}")
	public Report modifyReport(@PathVariable int id, @RequestBody Report report)
			throws HttpNotFoundException, HttpBadRequestException {
		if (id == report.getId()) {
			try {
				return service.modifyReport(id, report);
			} catch (NoSuchReportException e) {
				throw HttpNotFoundException.build(e);
			}
		}

		throw HttpBadRequestException.build(
				String.format("The id in the path(%d) and body(%d) does not match.", id, report.getId()));
	}

}
